<template>
  <div class="dashboard-container">
    <el-page-header @back="goBack">
      <template #content>
        <span class="text-large font-600 mr-3"> 配置中心 </span>
      </template>
    </el-page-header>
    <el-card style="height: 85px" mt-2>
      <el-avatar shape="square" class="blue" mr-2>
        <el-icon><Compass /></el-icon>
      </el-avatar>
      {{ appForm.title
      }}<span style="font-size: 12px" ml-1
        >( AppId: {{ appForm.app_id }} )</span
      >
    </el-card>
    <el-card mt-5>
      <template #header>
        <div class="flex justify-between">
          <div>
            <el-button type="success" @click="openDialog()"
              ><i-ep-plus />&nbsp;新增</el-button
            >
            <el-button type="primary" @click="release()"
              ><i-ep-promotion />&nbsp;发布</el-button
            >
            <el-button
              type="danger"
              v-if="removeIds.length > 0"
              @click="handleDelete()"
              ><i-ep-delete />删除</el-button
            >
          </div>
          <div>
            <div v-if="isShowSearchBtn" style="display: inline-block">
              <el-form
                ref="queryFormRef"
                :model="queryParams"
                :inline="true"
                class="search-form"
                mr-5
              >
                <el-form-item label="关键字" prop="title">
                  <el-input
                    v-model="queryParams.title"
                    placeholder="配置名称"
                    clearable
                    style="width: 200px"
                    @keyup.enter="handleQuery"
                  />
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click="handleQuery"
                    ><i-ep-search />搜索</el-button
                  >
                  <el-button @click="resetQuery">
                    <i-ep-refresh />
                    重置</el-button
                  >
                </el-form-item>
              </el-form>
            </div>
            <el-button
              class="ml-3"
              @click="handleSearchShowBtn"
              icon="Search"
              circle
            />
            <el-button
              class="ml-3"
              title="刷新"
              @click="handleQuery"
              icon="Refresh"
              circle
            />
          </div>
        </div>
      </template>
      <el-table
        :data="pageData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="ID" width="120" fixed>
          <template #default="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column
          label="配置名称"
          width="240"
          fixed
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column label="配置值" width="120" fixed>
          <template #default="scope">
            {{ scope.row.value }}
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template #default="scope">
            <el-tag
              v-if="scope.row.status == 1"
              key="WEB"
              type="success"
              effect="dark"
              round
            >
              已发布
            </el-tag>
            <el-tag
              v-if="scope.row.status == 0"
              key="APP"
              type="danger"
              effect="dark"
              round
            >
              未发布
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column property="remark" label="备注" />
        <el-table-column property="create_author" label="创建人" />
        <el-table-column property="created_at" label="添加时间" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              size="small"
              title="编辑"
              type="primary"
              circle
              @click="openDialog(scope.row.id)"
              icon="edit"
            />
            <el-button
              size="small"
              title="删除"
              icon="delete"
              circle
              @click="handleDelete(scope.row.id)"
              type="danger"
            />
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.p"
        v-model:limit="queryParams.limit"
        @pagination="handleQuery"
      />
    </el-card>
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="550">
      <el-form :model="configFormData" ref="ConfigFormRef" :rules="appRules">
        <el-form-item
          label="配置名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input
            v-model="configFormData.name"
            placeholder="请输入配置名称，多节点命名：name.child"
          />
        </el-form-item>
        <el-form-item label="配置值" :label-width="formLabelWidth" prop="value">
          <el-input v-model="configFormData.value" placeholder="请输入配置值" />
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth" prop="remark">
          <el-input v-model="configFormData.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Config",
  inheritAttrs: false,
});
import {
  getConfigPage,
  getConfigForm,
  addConfig,
  updateConfig,
  deleteConfig,
  releaseConfig,
} from "@/api/config";
import { ConfigQuery, ConfigPage } from "@/api/config/types";
import { getAppForm } from "@/api/application";
import { AppForm } from "@/api/application/types";
import { useTagsViewStore } from "@/store";
import { useRoute } from "vue-router";
import router from "@/router";
const dialogFormVisible = ref(false);
const dialogTitle = ref("");
const formLabelWidth = "140px";
const ConfigFormRef = ref(ElForm); // 用户表单
const loading = ref(false);
const queryFormRef = ref(ElForm); // 查询表单
const configFormData = reactive<ConfigPage>({
  sort: 0,
});
const appForm = reactive<AppForm>({
  sort: 0,
});
const removeIds = ref([]); // 删除ID集合 用于批量删除
const releaseIds = ref([]);
const isShowSearchBtn = ref(false);
const appRules = reactive({
  name: [{ required: true, message: "配置名称不能为空", trigger: "blur" }],
  value: [{ required: true, message: "配置值不能为空", trigger: "blur" }],
});
const pageData = ref<ConfigPage[]>();
const total = ref(0);
const queryParams = reactive<ConfigQuery>({
  p: 1,
  limit: 10,
});
//收起展开搜索按钮
function handleSearchShowBtn() {
  isShowSearchBtn.value = isShowSearchBtn.value === false;
}
const tagsViewStore = useTagsViewStore();
const route = useRoute();

/**
 * 打开弹窗
 * @param id 用户ID
 */
async function openDialog(id?: number) {
  dialogFormVisible.value = true;
  if (id) {
    dialogTitle.value = "编辑应用";
    getConfigForm(id).then(({ data }) => {
      Object.assign(configFormData, { ...data });
    });
  } else {
    dialogTitle.value = "创建应用";
  }
}

const handleSubmit = useThrottleFn(() => {
  ConfigFormRef.value.validate((valid: any) => {
    if (valid) {
      const ids = configFormData.id;
      loading.value = true;
      if (ids) {
        updateConfig(configFormData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
          })
          .finally(() => (loading.value = false));
      } else {
        addConfig(configFormData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 3000);

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialogFormVisible.value = false;
  ConfigFormRef.value.resetFields();
  ConfigFormRef.value.clearValidate();
  configFormData.id = undefined;
  handleQuery();
}

function release() {
  ElMessageBox.confirm("确认发布?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    releaseConfig({ ids: releaseIds.value, app_id: appForm.id }).then(() => {
      ElMessage.success("发布成功,生效时间将根据yaconf扩展配置");
      handleQuery();
    });
  });
}

function handleQuery() {
  loading.value = true;
  getConfigPage(queryParams)
    .then(({ data }) => {
      pageData.value = data.items;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

//删除
function handleDelete(id?: number) {
  const ids = id || removeIds.value;
  if (!ids) {
    ElMessage.warning("请勾选删除的数据");
    return;
  }
  ElMessageBox.confirm("确认删除?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteConfig({ ids: ids }).then(() => {
      ElMessage.success("删除成功");
      handleQuery();
    });
  });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.p = 1;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = releaseIds.value = selection.map((item: any) => item.id);
}
const goBack = () => {
  tagsViewStore.delView(route);
  history.back();
};

onMounted(() => {
  if (route.query.id) {
    getAppForm(<string>route.query.id)
      .then(({ data }) => {
        Object.assign(appForm, { ...data });
        configFormData.app_id = appForm.id;
      })
      .finally(() => {
        //loading.value = false;
      });
  } else {
    router.push({ path: "/dashboard", query: "" });
  }
  queryParams.app_id = <string>route.query.id;
  handleQuery();
});
</script>

<style lang="scss" scoped>
.dashboard-container {
  position: relative;
  margin-top: 50px;
  padding: 24px;
  .github-corner {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 1;
    border: 0;
  }

  .data-box {
    display: flex;
    justify-content: space-between;
    padding: 20px;
    font-weight: bold;
    color: var(--el-text-color-regular);
    background: var(--el-bg-color-overlay);
    border-color: var(--el-border-color);
    box-shadow: var(--el-box-shadow-dark);
  }

  .svg-icon {
    fill: currentcolor !important;
  }
  .box-card {
    text-align: center;
    font-size: 12px;
  }
  .menu_btn {
    display: inline-block;
    font-size: 14px;
    margin-left: 0;
    padding: 10px 55px 10px 10px;
    margin-bottom: 5px;
    border-radius: 5px;
  }
  .sky-blue {
    background-color: #3fc2f7;
  }
  .deep-blue {
    background-color: #4752e8;
  }
  .e158a6 {
    background-color: #e158a6;
  }
  .d6c1 {
    background-color: #33d6c1;
  }
  .purple {
    background-color: rgb(179, 127, 235);
  }
  .blue {
    background: #409eff;
  }
  .green {
    background-color: #67c23a;
  }
  .red {
    background-color: #f56c6c;
  }
  .yellow {
    background-color: #e6a23c;
  }
  .menu_btn span {
    margin-left: 8px;
  }
  .menu_btn:hover {
    background-color: #f2f2f2;
  }
  .el-link:hover {
    color: #000000;
  }
  .carousel-item {
    color: #475669;
    opacity: 0.75;
    margin: 0;
    text-align: center;
  }
}
.search-form .el-form-item {
  margin: 0px 15px 0px 0px;
}
</style>
